﻿using System;
using System.Linq;
using System.Web.Mvc;
using Microsoft.Ajax.Utilities;

namespace WebSite.Admin.Core
{
    //[AuthorizeFilterAttribute]
    public class BaseController : IdentityController
    {
        protected void ThrowWhenModelInvalid()
        {
            if (!ModelState.IsValid)
            {
                var firstState = ModelState.FirstOrDefault();
                if (!firstState.Key.IsNullOrEmpty())
                {
                    var message = AjaxMinExtensions.IfNotNull(firstState.Value.Errors.FirstOrDefault(),
                        i => i.ErrorMessage);
                    throw new Exception(message);
                }
            }
        }

        #region 通用JsonResult

        #region 成功
        /// <summary>
        /// 成功
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public JsonResult JsonSuccess(string msg)
        {
            return Json(new { status = "success", message = msg }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 失败
        /// <summary>
        /// 失败
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public JsonResult JsonError(string msg)
        {
            return Json(new { status = "error", message = msg }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #endregion
    }
}